package com.ff.controller;

import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ff.common.R;
import com.ff.entity.User;
import com.ff.service.UserService;
import com.ff.utils.SendPhone;
import com.ff.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) throws ClientException {
        if(StringUtils.isNotEmpty(user.getPhone())){
            //生成4位随机验证码或6位
            String code =ValidateCodeUtils.generateValidateCode(6).toString();
            log.info("验证码为{}",code);
            //发送短信服务
//            SendPhone.sendPhone(user.getPhone(), code);
            //存进session
//            session.setAttribute(user.getPhone(),code );
            //将生成的验证码缓存到Redis中，并设置有效时间为5分钟
            redisTemplate.opsForValue().set(user.getPhone(),code,5, TimeUnit.MINUTES);
            return R.success("手机验证码发送成功");
        }
        return R.success("短信发送失败");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");
        //从session中取验证码
        //String  codeInSession = (String) session.getAttribute(phone);
        //从redis中取验证码
        String  codeInSession= (String) redisTemplate.opsForValue().get(phone);
        if (code!=null||code.equals(codeInSession)){
            QueryWrapper<User> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("phone",phone);
            User user = userService.getOne(queryWrapper);
            if (user==null){
                user=new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //登录成功，删除redis中的验证码
            redisTemplate.delete(phone);
            session.setAttribute("user",user.getId());
            return R.success(user);
        }
        return R.error("登录失败");
    }
}
